<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="theme-color" content="#0078E7"><meta name="author" content="yangbo.wang"><meta name="copyright" content="yangbo.wang"><meta name="generator" content="Hexo 5.3.0"><meta name="theme" content="hexo-theme-yun"><title>Django视图简介 | Blog</title><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@900&amp;display=swap" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/star-markdown-css@0.1.22/dist/yun/yun-markdown.min.css"><script src="//at.alicdn.com/t/font_1140697_ed8vp4atwoj.js" async></script><script src="https://cdn.jsdelivr.net/npm/scrollreveal/dist/scrollreveal.min.js" defer></script><script>document.addEventListener("DOMContentLoaded", () => {
  [".post-card",".post-content img"].forEach((target)=> {
    ScrollReveal().reveal(target);
  })
});
</script><link rel="shortcut icon" type="image/svg+xml" href="/yun.svg"><link rel="mask-icon" href="/yun.svg" color="#0078E7"><link rel="alternate icon" href="/yun.ico"><link rel="preload" href="/css/hexo-theme-yun.css" as="style"><link rel="preload" href="/js/utils.js" as="script"><link rel="preload" href="/js/hexo-theme-yun.js" as="script"><link rel="prefetch" href="/js/sidebar.js" as="script"><link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin><script id="yun-config">
    const Yun = window.Yun || {};
    window.CONFIG = {"hostname":"example.com","root":"/","title":"你的月亮我的心","version":"1.4.0","mode":"dark","copycode":true,"page":{"isPost":true},"anonymous_image":"https://cdn.jsdelivr.net/gh/YunYouJun/cdn/img/avatar/none.jpg","say":{"api":"https://v1.hitokoto.cn","hitokoto":true},"fireworks":{"colors":["102, 167, 221","62, 131, 225","33, 78, 194"]}};
  </script><link rel="stylesheet" href="/css/hexo-theme-yun.css"><script src="/js/utils.js"></script><script src="/js/hexo-theme-yun.js"></script><meta name="description" content="视图 视图接受Web请求并且返回Web响应   视图就是一个python函数，被定义在views.py中   响应可以是一张网页的HTML内容，一个重定向，一个404错误等等   响应处理过程如下图：   URLconf 在settings.py文件中通过ROOT_URLCONF指定根级url的配置    urlpatterns是一个url()实例的列表    一个url()对象包括：    正则">
<meta property="og:type" content="article">
<meta property="og:title" content="Django视图简介">
<meta property="og:url" content="http://example.com/2021/01/17/django%E8%A7%86%E5%9B%BE/index.html">
<meta property="og:site_name" content="Blog">
<meta property="og:description" content="视图 视图接受Web请求并且返回Web响应   视图就是一个python函数，被定义在views.py中   响应可以是一张网页的HTML内容，一个重定向，一个404错误等等   响应处理过程如下图：   URLconf 在settings.py文件中通过ROOT_URLCONF指定根级url的配置    urlpatterns是一个url()实例的列表    一个url()对象包括：    正则">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2021-01-17T07:12:04.125Z">
<meta property="article:modified_time" content="2021-01-17T07:30:30.185Z">
<meta property="article:author" content="yangbo.wang">
<meta property="article:tag" content="Django">
<meta name="twitter:card" content="summary"><script src="/js/ui/mode.js"></script></head><body><script defer src="https://cdn.jsdelivr.net/npm/animejs@latest"></script><script defer src="/js/ui/fireworks.js"></script><canvas class="fireworks"></canvas><div class="container"><a class="sidebar-toggle hty-icon-button" id="menu-btn"><div class="hamburger hamburger--spin" type="button"><span class="hamburger-box"><span class="hamburger-inner"></span></span></div></a><div class="sidebar-toggle sidebar-overlay"></div><aside class="sidebar"><script src="/js/sidebar.js"></script><ul class="sidebar-nav"><li class="sidebar-nav-item sidebar-nav-toc hty-icon-button sidebar-nav-active" data-target="post-toc-wrap" title="Table of Contents"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-list-ordered"></use></svg></li><li class="sidebar-nav-item sidebar-nav-overview hty-icon-button" data-target="site-overview-wrap" title="Overview"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-passport-line"></use></svg></li></ul><div class="sidebar-panel" id="site-overview-wrap"><div class="site-info fix-top"><a class="site-author-avatar" href="/about/" title="yangbo.wang"><img width="96" loading="lazy" src="/Yun.png" alt="yangbo.wang"></a><div class="site-author-name"><a href="/about/">yangbo.wang</a></div><a class="site-name" href="/about/site.html">Blog</a><sub class="site-subtitle"></sub><div class="site-desciption"></div></div><nav class="site-state"><a class="site-state-item hty-icon-button icon-home" href="/" title="Home"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-home-4-line"></use></svg></span></a><div class="site-state-item"><a href="/archives/" title="Archives"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-archive-line"></use></svg></span><span class="site-state-item-count">8</span></a></div><div class="site-state-item"><a href="/categories/" title="Categories"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-folder-2-line"></use></svg></span><span class="site-state-item-count">2</span></a></div><div class="site-state-item"><a href="/tags/" title="Tags"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="site-state-item-count">9</span></a></div><a class="site-state-item hty-icon-button" href="/" title="文档"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-settings-line"></use></svg></span></a></nav><hr style="margin-bottom:0.5rem"><div class="links-of-author"><a class="links-of-author-item hty-icon-button" rel="noopener" title="微信 A18309169837" target="_blank" style="color:orange"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-wechat-2-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="QQ  1197213754" target="_blank" style="color:#12B7F5"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-qq-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" href="https://gitee.com/wyb_001" title="GitHub" target="_blank" style="color:#6e5494"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-github-line"></use></svg></a><a class="links-of-author-item hty-icon-button" rel="noopener" title="E-Mail 1197213754@qq.com" target="_blank" style="color:#8E71C1"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-mail-line"></use></svg></a></div><hr style="margin:0.5rem 1rem"><div class="links"><a class="links-item hty-icon-button" href="/about/" title="关于我" style="color:dodgerblue"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-genderless-line"></use></svg></a></div></div><div class="sidebar-panel sidebar-panel-active" id="post-toc-wrap"><div class="post-toc"><div class="post-toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%86%E5%9B%BE"><span class="toc-number">1.</span> <span class="toc-text">视图</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#URLconf"><span class="toc-number">2.</span> <span class="toc-text">URLconf</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8C%85%E5%90%AB%E5%85%B6%E5%AE%83%E7%9A%84URLconfs"><span class="toc-number">2.1.</span> <span class="toc-text">包含其它的URLconfs</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#URL%E7%9A%84%E5%8F%8D%E5%90%91%E8%A7%A3%E6%9E%90"><span class="toc-number">2.2.</span> <span class="toc-text">URL的反向解析</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#HttpResponse%E5%AF%B9%E8%B1%A1"><span class="toc-number">3.</span> <span class="toc-text">HttpResponse对象</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B1%9E%E6%80%A7"><span class="toc-number">3.1.</span> <span class="toc-text">属性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%95"><span class="toc-number">3.2.</span> <span class="toc-text">方法</span></a></li></ol></li></ol></div></div></div></aside><main class="sidebar-translate" id="content"><div id="post"><article class="post-block" itemscope itemtype="https://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://example.com/2021/01/17/django%E8%A7%86%E5%9B%BE/"><span hidden itemprop="author" itemscope itemtype="https://schema.org/Person"><meta itemprop="name" content="yangbo.wang"><meta itemprop="description"></span><span hidden itemprop="publisher" itemscope itemtype="https://schema.org/Organization"><meta itemprop="name" content="Blog"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">Django视图简介</h1><div class="post-meta"><div class="post-time" style="display:inline-block"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-calendar-line"></use></svg></span> <time title="Created: 2021-01-17 15:12:04" itemprop="dateCreated datePublished" datetime="2021-01-17T15:12:04+08:00">2021-01-17</time></div><div class="post-classify"><span class="post-category"> <span class="post-meta-item-icon" style="margin-right:3px;"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-folder-line"></use></svg></span><span itemprop="about" itemscope itemtype="https://schema.org/Thing"><a class="category" href="/categories/Python/" style="--text-color:var(--hty-text-color)" itemprop="url" rel="index"><span itemprop="text">Python</span></a></span></span><span class="post-tag"><span class="post-meta-divider">-</span><a class="tag" href="/tags/Django/" style="--text-color:var(--hty-text-color)"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="tag-name">Django</span></a></span></div></div></header><section class="post-body" itemprop="articleBody"><div class="post-content markdown-body" style="--smc-primary:#0078E7;"><h3 id="视图"><a href="#视图" class="headerlink" title="视图"></a>视图</h3><ul>
<li>视图接受Web请求并且返回Web响应  </li>
<li>视图就是一个python函数，被定义在views.py中  </li>
<li>响应可以是一张网页的HTML内容，一个重定向，一个404错误等等  </li>
<li>响应处理过程如下图： </li>
</ul>
<h3 id="URLconf"><a href="#URLconf" class="headerlink" title="URLconf"></a>URLconf</h3><ul>
<li><p>在settings.py文件中通过ROOT_URLCONF指定根级url的配置  </p>
</li>
<li><p>urlpatterns是一个url()实例的列表  </p>
</li>
<li><p>一个url()对象包括：  </p>
<ul>
<li>正则表达式  </li>
<li>视图函数  </li>
<li>名称name  </li>
</ul>
</li>
<li><p>编写URLconf的注意：  </p>
<ul>
<li>若要从url中捕获一个值，需要在它周围设置一对圆括号  </li>
<li>不需要添加一个前导的反斜杠，如应该写作’test/‘，而不应该写作’/test/‘  </li>
<li>每个正则表达式前面的r表示字符串不转义  </li>
</ul>
</li>
<li><p>请求的url被看做是一个普通的python字符串，进行匹配时不包括get或post请求的参数及域名  </p>
<pre><code>  http://www.itcast.cn/python/1/?i=1&amp;p=new，只匹配“/python/1/”部分</code></pre>
</li>
<li><p>正则表达式非命名组，通过位置参数传递给视图  </p>
<pre><code>  url(r&#39;^([0-9]+)/$&#39;, views.detail, name=&#39;detail&#39;),</code></pre>
</li>
<li><p>正则表达式命名组，通过关键字参数传递给视图，本例中关键字参数为id  </p>
<pre><code>  url(r&#39;^(?P&lt;id&gt;[0-9]+)/$&#39;, views.detail, name=&#39;detail&#39;),</code></pre>
</li>
<li><p>参数匹配规则：优先使用命名参数，如果没有命名参数则使用位置参数  </p>
</li>
<li><p>每个捕获的参数都作为一个普通的python字符串传递给视图  </p>
</li>
<li><p>性能：urlpatterns中的每个正则表达式在第一次访问它们时被编译，这使得系统相当快  </p>
</li>
</ul>
<h4 id="包含其它的URLconfs"><a href="#包含其它的URLconfs" class="headerlink" title="包含其它的URLconfs"></a>包含其它的URLconfs</h4><ul>
<li><p>在应用中创建urls.py文件，定义本应用中的urlconf，再在项目的settings中使用include()  </p>
<pre><code>  from django.conf.urls import include, url
      urlpatterns = [
      url(r&#39;^&#39;, include(&#39;booktest.urls&#39;, namespace=&#39;booktest&#39;)),
      ]</code></pre>
</li>
<li><p>匹配过程：先与主URLconf匹配，成功后再用剩余的部分与应用中的URLconf匹配  </p>
<pre><code>  请求http://www.itcast.cn/booktest/1/
  在sesstings.py中的配置：  
  url(r&#39;^booktest/&#39;, include(&#39;booktest.urls&#39;, namespace=&#39;booktest&#39;)),
  在booktest应用urls.py中的配置  
  url(r&#39;^([0-9]+)/$&#39;, views.detail, name=&#39;detail&#39;),
  匹配部分是：/booktest/1/
  匹配过程：在settings.py中与“booktest/”成功，再用“1/”与booktest应用的urls匹配  </code></pre>
</li>
<li><p>使用include可以去除urlconf的冗余  </p>
</li>
<li><p>参数：视图会收到来自父URLconf、当前URLconf捕获的所有参数  </p>
</li>
<li><p>在include中通过namespace定义命名空间，用于反解析  </p>
</li>
</ul>
<h4 id="URL的反向解析"><a href="#URL的反向解析" class="headerlink" title="URL的反向解析"></a>URL的反向解析</h4><ul>
<li><p>如果在视图、模板中使用硬编码的链接，在urlconf发生改变时，维护是一件非常麻烦的事情  </p>
</li>
<li><p>解决：在做链接时，通过指向urlconf的名称，动态生成链接地址  </p>
</li>
<li><p>视图：使用django.core.urlresolvers.reverse()函数  </p>
</li>
<li><p>模板：使用url模板标签  </p>
<h3 id="HttpResponse对象"><a href="#HttpResponse对象" class="headerlink" title="HttpResponse对象"></a>HttpResponse对象</h3></li>
<li><p>在django.http模块中定义了HttpResponse对象的API  </p>
</li>
<li><p>HttpRequest对象由Django自动创建，HttpResponse对象由程序员创建  </p>
</li>
<li><p>不调用模板，直接返回数据  </p>
<pre><code>  #coding=utf-8
  from django.http import HttpResponse

  def index(request):
      return HttpResponse(&#39;你好&#39;)  </code></pre>
</li>
<li><p>调用模板  </p>
<pre><code>  from django.http import HttpResponse
  from django.template import RequestContext, loader

  def index(request):
      t1 = loader.get_template(&#39;polls/index.html&#39;)
      context = RequestContext(request, &#123;&#39;h1&#39;: &#39;hello&#39;&#125;)
      return HttpResponse(t1.render(context))  </code></pre>
</li>
</ul>
<h4 id="属性"><a href="#属性" class="headerlink" title="属性"></a>属性</h4><ul>
<li>content：表示返回的内容，字符串类型  </li>
<li>charset：表示response采用的编码字符集，字符串类型  </li>
<li>status_code：响应的HTTP响应状态码  </li>
<li>content-type：指定输出的MIME类型  </li>
</ul>
<h4 id="方法"><a href="#方法" class="headerlink" title="方法"></a>方法</h4><ul>
<li>init ：使用页内容实例化HttpResponse对象  </li>
<li>write(content)：以文件的方式写  </li>
<li>flush()：以文件的方式输出缓存区  </li>
<li>set_cookie(key, value=’’, max_age=None, expires=None)：设置Cookie  </li>
<li>key、value都是字符串类型  </li>
<li>max_age是一个整数，表示在指定秒数后过期  </li>
<li>expires是一个datetime或timedelta对象，会话将在这个指定的日期/时间过期，注意datetime和timedelta值只有在使用PickleSerializer时才可序列化  </li>
<li>max_age与expires二选一  </li>
<li>如果不指定过期时间，则两个星期后过期  </li>
</ul>
</div><ul class="post-copyright"><li class="post-copyright-author"><strong>Post author: </strong>yangbo.wang</li><li class="post-copyright-link"><strong>Post link: </strong><a href="http://example.com/2021/01/17/django%E8%A7%86%E5%9B%BE/" title="Django视图简介">http://example.com/2021/01/17/django%E8%A7%86%E5%9B%BE/</a></li><li class="post-copyright-license"><strong>Copyright Notice: </strong>All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank" rel="noopener" title="CC BY-NC-SA 4.0 "><svg class="icon"><use xlink:href="#icon-creative-commons-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-by-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-nc-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-sa-line"></use></svg></a> unless otherwise stated.</li></ul></section></article><div class="post-nav"><div class="post-nav-item"></div><div class="post-nav-item"><a class="post-nav-next" href="/2021/01/17/django%20%E6%A8%A1%E5%9E%8B%E6%9F%A5%E8%AF%A2/" rel="next" title="模型查询"><span class="post-nav-text">模型查询</span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-right-s-line"></use></svg></a></div></div></div></main><footer class="sidebar-translate" id="footer"><div class="copyright"><span>&copy; 2019 – 2021 </span><span class="with-love" id="animate"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-cloud-line"></use></svg></span><span class="author"> yangbo.wang</span></div><div class="powered"><span>Powered by <a href="https://hexo.io" target="_blank" rel="noopener">Hexo</a> v5.3.0</span><span class="footer-separator">|</span><span>Theme - <a rel="noopener" href="https://github.com/YunYouJun/hexo-theme-yun" target="_blank"><span>Yun</span></a> v1.4.0</span></div></footer><a class="hty-icon-button" id="goUp" aria-label="back-to-top" href="#"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-up-s-line"></use></svg><svg class="progress-circle-container" viewBox="0 0 100 100"><circle class="progress-circle" id="progressCircle" cx="50" cy="50" r="48" fill="none" stroke="#0078E7" stroke-width="2" stroke-linecap="round"></circle></svg></a></div></body></html>